package components

import (
	"context"
	"encoding/base64"
	"fmt"
	"kafkademo/config"
	"kafkademo/pkg/log"

	"github.com/illidaris/aphrodite/component/gormex"
	"github.com/spf13/cast"
	"gorm.io/gorm"
)

func InitMySql() {
	initMysqlFrmConfig("main", "writer", gormex.MySqlComponent.NewWriter)
	initMysqlFrmConfig("main", "reader", gormex.MySqlComponent.NewReader)
}

func initMysqlFrmConfig(name string, key string, f func(id string, items ...*gorm.DB)) {
	ctx := context.Background()
	v := config.Get(fmt.Sprintf("mysql.%s.%s", name, key))
	dsnDes := cast.ToStringSlice(v)
	for _, dsnDe := range dsnDes {
		dsnBs, err := base64.RawStdEncoding.DecodeString(dsnDe)
		if err != nil {
			log.Error(context.TODO(), err.Error())
			continue
		}
		db, err := gormex.NewMySqlClient(string(dsnBs), gormex.NewLogger())
		log.Info(ctx, "%s %s init err %s", name, key, err)
		if err != nil {
			log.Error(context.TODO(), err.Error())
		}
		f(name, db)
	}
}
